package com.aisile.user.service.impl;

import cn.hutool.core.util.DesensitizedUtil;
import com.aisile.common.exception.CustomExceptionCatch;
import com.aisile.model.common.dtos.ResponseResult;
import com.aisile.model.common.enums.AppHttpCodeEnum;
import com.aisile.model.user.dtos.LoginDto;
import com.aisile.model.user.pojos.ApUser;
import com.aisile.user.mapper.ApUserMapper;
import com.aisile.user.service.ApUserLoginService;
import com.aisile.utils.common.AppJwtUtil;
import com.aisile.utils.common.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther:yry
 * @Date:2024/1/13 0013
 * @VERSON:1.0
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        if(loginDto == null){
            CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<String,Object> resultMap = new HashMap<>();
        if(!StringUtils.isEmpty(loginDto.getPhone()) && !StringUtils.isEmpty(loginDto.getPassword())){
            // 用户登录
            ApUser apUser =  apUserMapper.selectOne(
                    Wrappers.<ApUser>lambdaQuery().eq(
                            ApUser::getPhone, loginDto.getPhone()
                    )
            );
            if(apUser == null){
                CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            if(!BCrypt.checkpw(loginDto.getPassword(),apUser.getPassword())){
                CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 手动脱敏
            // 数据脱敏： 手机号脱敏  、密码欧敏等等
            apUser.setPhone(DesensitizedUtil.mobilePhone(apUser.getPhone()));
            apUser.setPassword("******");
            String token =  AppJwtUtil.getToken(apUser.getId().longValue());
            resultMap.put("user",apUser);
            resultMap.put("token",token);
        }else{
            // 不登录 看看
            if(loginDto.getEquipmentId() == null){
                CustomExceptionCatch.catchApp(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            String token =  AppJwtUtil.getToken(0L);
            resultMap.put("token",token);
        }

        return ResponseResult.okResult(resultMap);
    }
}
